package IO.url;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author 15594
 */
public class URLTest {
    public static void main(String[] args)  {
        InputStream inputStream = null;
        try {
            URL url = new URL("https://blog.csdn.net/a123123sdf/article/details/119357869");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //创建连接
            connection.connect();

            System.out.println("状态码："+connection.getResponseCode());
            System.out.println("响应信息："+connection.getResponseMessage());

            inputStream = connection.getInputStream();
            download(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        byte [] bytes = new byte[1024];
//        int len = 0;
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        while ((len = inputStream.read(bytes))!=-1){
//            byteArrayOutputStream.write(bytes,0,len);
//        }
//        System.out.println(byteArrayOutputStream.toString());
    }

    private static void download(InputStream inputStream) {

        String path = System.getProperties().getProperty("user.home");

        BufferedOutputStream bos = null;

        try {
            System.out.println(path + File.separator + "index.html");
            FileOutputStream outputStream = new FileOutputStream(path + File.separator + "index.html");
            bos = new BufferedOutputStream(outputStream);
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes))!=-1){
                bos.write(bytes,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
